
package edu.chl.vrangogym.beans.ctrl;

import edu.chl.vrangogym.beans.backing.LoginBackingBean;
import edu.chl.vrangogym.persistence.entities.User;
import edu.chl.vrangogym.persistence.impl.UserFacade;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
 *
 * @author Anders
 */
@ManagedBean(name = "LoginCtrl")
@RequestScoped
public class LoginCtrlBean implements Serializable {
    
    @ManagedProperty(value="#{Login}")
    LoginBackingBean loginBackingBean;
    
    public void setLoginBackingBean(LoginBackingBean loginBackingBean){
        this.loginBackingBean = loginBackingBean;
    }
    
    @EJB
    private UserFacade userFacade;
    
    private boolean modalRendered = false;
    
    private String message="null";

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isModalRendered() {
        return modalRendered;
    }

    public void setModalRendered(boolean modalRendered) {
        this.modalRendered = modalRendered;
    }

    /** Creates a new instance of LoginCtrlBean */
    public LoginCtrlBean() {
    }
    
    @PostConstruct
    public void postConstruct() {
    }

    /**
     * Tries to login a user from submitted form data
     * @param evt
     * @return Returns a boolean value indicating wether login was successful or not.
     */
    public void login(ActionEvent evt) {
        // Get user from database
        User user = (User) userFacade.find(loginBackingBean.getUsername());
        
        // Validate input against data stored in database
        if(loginBackingBean.getPassword().equals(user.getPassword())) {
            FacesContext.getCurrentInstance().getExternalContext()
                    .getSessionMap().put("Auth.user", user);
        }
    }
    
    public void toggleRegisterModal(ActionEvent event) {
        modalRendered = !modalRendered;
    }
    
}
